package com.sann.demo.dao.impl;


import com.sann.demo.beans.Account;
import com.sann.demo.dao.IAccountDao;
import com.sann.demo.util.ConnectionUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

   @Autowired
    private QueryRunner runner;

    @Autowired
    private ConnectionUtil connectionUtil;

    @Override
    public void updateAccount(Account account) {
        try {
            runner.update(connectionUtil.getThreadConnection(),
                    "update tb_account set name=?, money=? where id=?",
                    account.getName(),account.getMoney(),account.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findByName(String accountName) {
        try {
            List<Account> accounts = runner.query(connectionUtil.getThreadConnection(),
                    "select * from tb_account where name=?",
                    new BeanListHandler<Account>(Account.class), accountName);
            if(accounts==null || accounts.size()==0){
                return null;
            }
            if(accounts.size()>1){
                throw new RuntimeException("账户不唯一");
            }
            return accounts.get(0);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
